package com.rcp.manager;

/* Restaurant Control Program >> Restaurant Manager */


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Array;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;


@WebServlet("/EmployeesTable")
public class EmployeesTable extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	Connection connection = Nexus.connection;
	//ArrayList<Employee> employees;
	//ArrayList<Integer> inMemory;

    public EmployeesTable() {
        super();
        //this.employees = new ArrayList<Employee>();
        //this.inMemory = new ArrayList<Integer>();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		ArrayList<Employee> employees =  new ArrayList<Employee>();
		
		//Check if connection is active
		if(this.connection == null){
			establishConnection();
		} else
			try {
				if(this.connection.isClosed()){
					establishConnection();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		
		//Extract Query
		int employeeID = 0;
		String firstname = "";
		String lastname = "";
		String password = "";
		int status = 0;
		
		//Get result set
		try {
			String preparedQuery = "SELECT EmployeeID, FirstName, LastName, password, status FROM Employees;";
			
			PreparedStatement ps = (PreparedStatement) connection.prepareStatement(preparedQuery);
			ResultSet results = ps.executeQuery();
			
			//Purge deleted records
			//purge(results);
			
			
			while(results.next()){
				employeeID = results.getInt("EmployeeId");
				
				/*if(inMemory.contains(employeeID)){
					continue;
				}
				else{*/
				firstname = results.getString("firstname");
				lastname = results.getString("lastname");
				password = results.getString("password");
				status = results.getInt("status");
					
				employees.add(new Employee(employeeID, firstname, lastname, password, status));
					//this.inMemory.add(employeeID);
				//}
			}
	
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		//Print out Employees
		out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

		out.println("<html>");
		
		out.println("<head>");

		out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">");
		
		out.println("<link href=\"resources/CSS/Featured.css\" rel=\"stylesheet\" type=\"text/css\"/>");

		out.println("<title>Employee Creation</title>");

		out.println("</head>");

		out.println("<body>");

		//Loop & Print through employees array
		/*Employee current = null;
		
		for(int i = 0; i < this.employees.size(); i++){
			current = employees.get(i);
			
			out.println("[Employee ID: " + current.getEmployeeID() + "] -  ");
			out.println("[First Name: " + current.getFirstname() + "] -  ");
			out.println("[Last Name: " + current.getLastname() + "] -  ");
			out.println("[Password: " + current.getPassword() + "] -  ");
			out.println("[Status: " + current.getStatus() + "]  ");
			out.println("<br /><br />");
		}*/
		
		//Get table dimensions
		int dimensions = getTableDimensions(employees.size());
		
		if(dimensions > 3){
			dimensions = 3;
		}
		
		out.println("<div class='container'>");
		
		out.println("<form name='chosen' action='StaffManagerServlet' method='get'>");
		
		out.println("<table class='staffTable'>");
		

		//Loop & Print through employees array
		Employee current = null;
		int counter = 0;
		
		for(int i = 0; i < employees.size(); i++){
			current = employees.get(i);
			
			//if(inMemory.contains(current.getEmployeeID())){
				if(counter == dimensions || i == 0){
					out.println("<tr>");
				}
				
					out.println("<td class='block'>");
					
					out.println("<button type='submit' name='selected' class='cell' value='" + current.getEmployeeID() + 
								"'>"  + current.getFirstname() + " " + current.getLastname() + "</button>");
					out.println("<br /><br />");
					
					out.println("</td>");
					
					counter++;
				
				if(counter == dimensions){
					out.println("</tr>");
					counter = 0;
				}
			//}
		}
		
		
		out.println("</table>");
		
		out.println("</form>");
		
		out.println("</div>");
		
		out.println("</body>");
		
		out.println("</html>");
		
		out.close();
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}
	
	private int getTableDimensions(int size){
		int dimensions = 0;
		
		if(size > 0){
			dimensions = (int) Math.floor(Math.sqrt(size));
			
			if(dimensions < 1){
				return 1;
			}
			
			return dimensions;
		}
		
		return 0;
	}
	
	public void establishConnection(){
		
		String dbURL = "jdbc:mysql://cs3.calstatela.edu:3306/cs437group01";
		String dbName = "";
		String username = "cs437group01";
		String password = "VHj#dj!v";
		String driver = "com.mysql.jdbc.Driver";
		 
		/*
		String dbURL = "jdbc:mysql://localhost:3306/";
		String dbName = "rcp";
		String username = "root";
		String password = "sesame";
		String driver = "com.mysql.jdbc.Driver";
		*/
		
		try {
			Class.forName(driver).newInstance();
			Nexus.connection = (Connection) DriverManager.getConnection(dbURL + dbName, username, password);
			this.connection = Nexus.connection;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//Fix
	/*private void purge(ResultSet results){
		ArrayList<Integer> rSet = new ArrayList<Integer>();
		
		try {
			while( results.next()){
				rSet.add(results.getInt("EmployeeID"));
			}
			
			//Reset ResultSet pointer
			results.beforeFirst();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		for(int i : inMemory){
			if(!(rSet.contains(i))){
				inMemory.remove(i);
			}
		}
		
		/*System.out.println("Size: " + inMemory.size());
		for(int i: inMemory){
			System.out.println(i);
		}
	}*/

}
